package cn.edu.xmu.oomall.order.dao;

import cn.edu.xmu.javaee.core.exception.BusinessException;
import cn.edu.xmu.javaee.core.mapper.RedisUtil;
import cn.edu.xmu.javaee.core.model.ReturnNo;
import cn.edu.xmu.oomall.order.dao.bo.OrderItem;
import cn.edu.xmu.oomall.order.mapper.OrderItemPoMapper;
import cn.edu.xmu.oomall.order.mapper.po.OrderItemPo;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import cn.edu.xmu.javaee.core.util.CloneFactory;

import java.io.Serializable;
import java.util.Objects;
import java.util.Optional;

/**
 * @author 谢传艳
 * @date 2024/12/11
 */
@Repository
@RequiredArgsConstructor
public class OrderItemDao {
    private static final String KEY = "OI%d";

    private final RedisUtil redisUtil;
    private final OrderItemPoMapper orderItemPoMapper;

    @Value("${oomall.order.timeout}")
    private Long timeout;

    private void build(OrderItem bo){
        bo.setOrderItemDao(this);
    }


    private OrderItem build(OrderItemPo po, Optional<String> redisKey) throws RuntimeException{
        OrderItem bo = CloneFactory.copy(new OrderItem(), po);
        this.build(bo);
        redisKey.ifPresent(key -> redisUtil.set(key, bo, timeout));
        return bo;
    }

    /**
     * 根据id查找订单明细
     * @param oid 订单明细id
     * @return 订单明细对象
     */
    public OrderItem findById(Long oid) {
        String key = String.format(KEY, oid);
        OrderItem bo = (OrderItem) redisUtil.get(key);
        if(Objects.isNull(bo)){
            Optional<OrderItemPo> orderItemPo = orderItemPoMapper.findById(oid);
            if (orderItemPo.isPresent()) {
                return build(orderItemPo.get(), Optional.of(key));
            }else {
                throw new BusinessException(ReturnNo.RESOURCE_ID_NOTEXIST, String.format(ReturnNo.RESOURCE_ID_NOTEXIST.getMessage(),"订单明细", oid));
            }
        }
        return bo;
    }

    /**
     * 更新订单明细
     * @param orderItem 订单明细对象
     */
    public OrderItem save(OrderItem orderItem) {
        String key = String.format(KEY, orderItem.getId());
        OrderItemPo po = CloneFactory.copy(new OrderItemPo(), orderItem);
        OrderItemPo orderItemPo = orderItemPoMapper.save(po);
        redisUtil.del(key);
        return build(orderItemPo, Optional.of(key));
    }
}
